using System;

namespace MinesweeperPlus.Scripts.Objects
{
    public class Timer
    {
        #region Actions
        public Action<int> OnTick;
        #endregion

        #region Variables
        private Game _game;
        private float _interval;
        private float _currentTime;
        public bool _isSubscribed;
        public int _numberOfTicks;
        #endregion

        #region Timer Methods
        public Timer(Game game, float intervalInSeconds)
        {
            _game = game;
            _interval = intervalInSeconds;
            _isSubscribed = false;

            Reset();
        }

        public void Start() 
        {
            if (_isSubscribed)
                return;

            _game.OnFixedUpdate += TimerTick;
            _isSubscribed = true;
        }
        public void Stop() 
        { 
            if (!_isSubscribed)
                return;

            _game.OnFixedUpdate -= TimerTick;
            _isSubscribed = false;
        }
        public void Reset() 
        { 
            _currentTime = 0;
            _numberOfTicks = 0;
            OnTick?.Invoke(_numberOfTicks);
        }
        #endregion

        #region Other Methods
        private void TimerTick(float deltaTime)
        {
            _currentTime += deltaTime;
            if (_currentTime > _interval)
            {
                _currentTime = 0;
                OnTick?.Invoke(++_numberOfTicks);
            }
        }
        #endregion
    }
}
